<?php

namespace App\Http\Services;

use App\Http\Repositories\Daos\Cluster\ClusterDao;
use App\Http\Requests\Cluster;
use App\Http\Requests\UserContext;
use App\Http\Traits\Errors;
use App\Http\Traits\GlobalConstant;
use App\Models\ClusterMember;
use Illuminate\Support\Facades\DB;

class ClusterService extends BaseService
{
    use Errors;

    protected $clusterDao;

    public function __construct(ClusterDao $clusterDao)
    {
        $this->clusterDao = $clusterDao;
    }

    public function add(UserContext $userContext, Cluster $cluster)
    {
        $userId = $userContext->getId();
        $data   = $cluster->validationData();
        $id     = request('id') ?? 0;
        DB::beginTransaction();
        try {
            if (!empty($id)) {
                $this->clusterDao->update($id, ['name' => $data['name']]);
                ClusterMember::where('user_id', $userId)->where('cluster_id', $id)->update(['nickname' => $data['nickname']]);
            } else {
                $model = $this->clusterDao->save(['name' => $data['name'], 'user_id' => $userId]);
                ClusterMember::create(['cluster_id' => $model->id, 'user_id' => $userId, 'nickname' => $data['nickname']]);
                $id = $model->id;
            }
            DB::commit();
            return ['id' => $id, 'name' => $data['name']];

        } catch (\Exception $exception) {
            DB::rollBack();
            $this->showError($exception->getMessage());
        }
    }

    public function lists(UserContext $userContext)
    {
        $userId = $userContext->getId();
        $page   = request('page') ?? 1;
        $size   = request('size') ?? 3;
        $field  = ['*'];
        $offset = ($page * $size) - $size;
        $list   = ClusterMember::where('user_id', $userId)->whereIn('cluster_id', function ($q) {
            $q->where('status', 1)->select(['id'])->from('cluster');
        })->with(["clusterInfo" => function ($query) {
            $query->select(['id', 'name', 'created_at']);
        }])->withCount(["dragonInfo"])->withCount(["selfCluster"])->orderBy('created_at', 'desc')->limit($size)->offset($offset)->get($field);
        if (!empty($list)) {
            foreach ($list as &$item) {
                $item['role_str']     = GlobalConstant::getRoleMap($item['role']);
                $item['cluster_name'] = $item->clusterInfo->name;
            }
            unset($item);
        }
        return $list;
    }

    public function dissolve(UserContext $userContext)
    {
        $userId = $userContext->getId();
        $id     = request('id') ?? 0;
        if (empty($id)) $this->showError('请传入需要解散的群');
        DB::beginTransaction();
        try {
            $rel = $this->clusterDao->getModel()->where('id', $id)->where('user_id', $userId)->update(['status' => 0]);
            if ($rel === false) {
                $this->showError('解散失败');
            }
            DB::table('cluster_member')->where('cluster_id', $id)->update(['status' => 0]);
            DB::commit();
            return true;
        } catch (\Exception $exception) {
            DB::rollBack();
            $this->showError('解散失败,联系管理员');
        }
    }

    public function detail(UserContext $userContext)
    {
        $id     = request('id') ?? 0;
        $userId = $userContext->getId();
        $info   = $this->clusterDao->getModel()->where('id', $id)->withCount(["clusterMember"])->first();
        if ($info) {
            $memberInfo       = ClusterMember::where('cluster_id', $id)->where('user_id', $userId)->first(['nickname', 'role']);
            $info['nickname'] = $memberInfo['nickname'];
            $info['role']     = $memberInfo['role'];
        }
        return $info;
    }

    public function memberLists()
    {
        $clusterId = request('id') ?? 0;
        $page      = request('page') ?? 1;
        $size      = request('size') ?? 3;
        $field     = ['*'];
        $offset    = ($page * $size) - $size;
        $lists     = ClusterMember::where('cluster_id', $clusterId)->where('status', 1)->with(["userInfo" => function ($query) {
            $query->select(['id', 'avatar']);
        }])->orderBy('role')->limit($size)->offset($offset)->get($field);
        if (!empty($lists)) {
            foreach ($lists as &$item) {
                $item['role_str'] = GlobalConstant::getRoleMap($item['role']);
            }
            unset($item);
        }
        return $lists;
    }

    public function setAdmin(UserContext $userContext)
    {
        $id            = request('id') ?? 0;
        $requestUserId = request('user_id') ?? 0;
        $userId        = $userContext->getId();
        $member        = ClusterMember::where('id', $id)->where('user_id', $requestUserId)->first();
        if (empty($member)) $this->showError('成员不存在');
        $cluster = $this->clusterDao->getOne(['id' => $member['cluster_id']]);
        if (empty($cluster)) $this->showError('群不存在');
        if ($userId != $cluster['user_id']) {
            $this->showError('非群主不能操作');
        }
        $role         = $member->role == 2 ? 3 : 2;
        $message      = $member->role == 3 ? '设置成功！管理员拥有该组内接龙的管理权限' : '取消成功！已取消该组员的组内接龙管理权限';
        $member->role = $role;
        $member->save();
        return compact("message");
    }

    public function removeMember(UserContext $userContext)
    {
        $id            = request('id') ?? 0;
        $userId        = $userContext->getId();
        $requestUserId = request('user_id') ?? 0;
        $member        = ClusterMember::where('id', $id)->where('user_id', $requestUserId)->first();
        if (empty($member)) $this->showError('成员不存在');
        $cluster = $this->clusterDao->getOne(['id' => $member['cluster_id']]);
        if (empty($cluster)) $this->showError('群不存在');
        if ($userId != $cluster['user_id']) {
            $this->showError('非群主不能操作');
        }
        $member->status = 0;
        $member->save();
        return true;
    }

    public function addMember(UserContext $userContext)
    {
        $clusterId = request('id') ?? 0;
        $userId    = $userContext->getId();
        $nickname  = $userContext->getNickName();
        if (empty($clusterId || empty($userId))) $this->showError('参数异常');
        $clusterInfo = $this->clusterDao->getOne(['id' => $clusterId]);
        if (empty($clusterInfo) || $clusterInfo['status'] == 0) $this->showError('群不存在或已解散');
        $member = ClusterMember::where('cluster_id', $clusterId)->where('user_id', $userId)->first();
        if ($member) {
            if ($member['status'] == 1) return ['status' => 0, 'message' => '已在当前群组中'];
            if ($member['status'] == 0) return ['status' => 1, 'message' => '链接已过期'];
        }
        ClusterMember::create(['cluster_id' => $clusterId, 'user_id' => $userId, 'role' => 3, 'nickname' => $nickname]);
        return ['status' => 0, 'message' => '入群成功'];
    }
}
